<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- ===== 核心搜索条件（常用） ===== -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillCode_FormItem" prop="BillCode">
							<template #label>
								<WtmLabelTooltip label="单据编号" tooltip="单据的唯一编号" />
							</template>
							<el-input v-model="searchData.BillCode" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Applicant_FormItem" prop="Applicant">
							<template #label>
								<WtmLabelTooltip label="申请人" tooltip="采购申请的发起人姓名" />
							</template>
							<el-input v-model="searchData.Applicant" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillStatus_FormItem" prop="BillStatus">
							<template #label>
								<WtmLabelTooltip label="单据状态" tooltip="单据的处理状态" />
							</template>
							<el-select v-model="searchData.BillStatus" clearable>
								<el-option key="草稿" value="草稿" label="草稿"></el-option>
								<el-option key="正文" value="正文" label="正文"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="WorkflowStatus_FormItem" prop="WorkflowStatus">
							<template #label>
								<WtmLabelTooltip label="工作流状态" tooltip="工作流的执行状态" />
							</template>
							<el-select v-model="searchData.WorkflowStatus" clearable>
								<el-option key="待提交" value="待提交" label="待提交"></el-option>
								<el-option key="提交中" value="提交中" label="提交中"></el-option>
								<el-option key="审核中" value="审核中" label="审核中"></el-option>
								<el-option key="已完成" value="已完成" label="已完成"></el-option>
								<el-option key="已取消" value="已取消" label="已取消"></el-option>
								<el-option key="待处理" value="待处理" label="待处理"></el-option>
								<el-option key="处理中" value="处理中" label="处理中"></el-option>
								<el-option key="已处理" value="已处理" label="已处理"></el-option
							></el-select>
						</el-form-item>
					</el-col>

					<!-- ===== 高级搜索条件（可展开） ===== -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="RequestDate_FormItem" prop="RequestDate">
								<template #label>
									<WtmLabelTooltip label="申请日期" tooltip="采购申请单的提交日期" />
								</template>
								<el-date-picker v-model="searchData.RequestDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="NeedDate_FormItem" prop="NeedDate">
								<template #label>
									<WtmLabelTooltip label="需求日期" tooltip="物料的期望到货日期" />
								</template>
								<el-date-picker v-model="searchData.NeedDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PurchaseType_FormItem" prop="PurchaseType">
								<template #label>
									<WtmLabelTooltip label="采购类型" tooltip="采购类型：常规、备用、设备新增、安全新增等" />
								</template>
								<el-select v-model="searchData.PurchaseType" clearable>
									<el-option key="备品备件" value="备品备件" label="常规"></el-option>
									<el-option key="设备新增" value="设备新增" label="设备新增"></el-option>
									<el-option key="安全新增" value="安全新增" label="安全新增"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaterialType_FormItem" prop="MaterialType">
								<template #label>
									<WtmLabelTooltip label="物料类型" tooltip="采购物料的分类" />
								</template>
								<el-select v-model="searchData.MaterialType" clearable>
									<el-option key="备品备件" value="备品备件" label="备品备件"></el-option>
									<el-option key="化工小料" value="化工小料" label="化工小料"></el-option>
									<el-option key="大宗原材料" value="大宗原材料" label="大宗原材料"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PurchaseMethod_FormItem" prop="PurchaseMethod">
								<template #label>
									<WtmLabelTooltip label="采购方式" tooltip="采购方式：集采、招标等" />
								</template>
								<el-select v-model="searchData.PurchaseMethod" clearable>
									<el-option key="集采" value="集采" label="集采"></el-option>
									<el-option key="招标" value="招标" label="招标"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="UrgencyLevel_FormItem" prop="UrgencyLevel">
								<template #label>
									<WtmLabelTooltip label="紧急程度" tooltip="采购的紧急程度：一般、紧急" />
								</template>
								<el-select v-model="searchData.UrgencyLevel" clearable>
									<el-option key="一般" value="一般" label="一般"></el-option>
									<el-option key="紧急" value="紧急" label="紧急"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Approver_FormItem" prop="Approver">
								<template #label>
									<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
								</template>
								<el-input v-model="searchData.Approver" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ApprovalTime_FormItem" prop="ApprovalTime">
								<template #label>
									<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
								</template>
								<el-date-picker v-model="searchData.ApprovalTime" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="GroupId_FormItem" prop="GroupId">
								<template #label>
									<WtmLabelTooltip label="所属部门" tooltip="关联的部门" />
								</template>
								<el-select v-model="searchData.GroupId" :data="stateData.AllSysGroups" clearable>
									<el-option v-for="item in stateData.AllSysGroups" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="OrgId_FormItem" prop="OrgId">
								<template #label>
									<WtmLabelTooltip label="所属机构" tooltip="关联的机构" />
								</template>
								<el-select v-model="searchData.OrgId" :data="stateData.AllSysOrgs" clearable>
									<el-option v-for="item in stateData.AllSysOrgs" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Remark_FormItem" prop="Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="单据的备注信息" />
								</template>
								<el-input v-model="searchData.Remark" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBill/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBill/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBill/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPurchaseRequestBill/SysPurchaseRequestBillExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysPurchaseRequestBill/Edit'"
								v-if="scope.row.BillStatus === '草稿'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-if="scope.row.CanApprove == 'true'"
								:is-text="true"
								icon="-o"
								type="warning"
								button-text="审批"
								@@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-else
								v-auth="'/api/SysPurchaseRequestBill/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysPurchaseRequestBill/BatchDelete'"
								v-if="scope.row.BillStatus === '草稿'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="采购申请;true;HengTong.Areas.SupplyChain.Controllers;SysPurchaseRequestBill">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysPurchaseRequestBillApi as api } from '/@/views/supplychain/syspurchaserequestbill/api';
import { ISysPurchaseRequestBillView, ISysPurchaseRequestBillQuery } from '/@/views/supplychain/syspurchaserequestbill/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysPurchaseRequestBillQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysGroups: [] as ISysSelectType[],
	AllSysOrgs: [] as ISysSelectType[],
});

const searchData = ref<ISysPurchaseRequestBillQuery>({
	Applicant: null,
	RequestDate: null,
	NeedDate: null,
	PurchaseType: null,
	MaterialType: null,
	PurchaseMethod: null,
	UrgencyLevel: null,
	Approver: null,
	ApprovalTime: null,
	GroupId: null,
	OrgId: null,
	BillCode: null,
	BillStatus: null,
	WorkflowStatus: null,
	Remark: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）- 按优先级和重要性排列
	header: [
		// 1️⃣ 单据识别信息（最重要）
		{ title: '单据编号', key: 'BillCode', type: 'text', isCheck: true },
		{
			title: '单据状态',
			key: 'BillStatus',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysPurchaseRequestBillView) => {
				const statusMap: Record<string, string> = {
					草稿: 'info',
					正文: 'warning',
				};
				return statusMap[row.BillStatus || ''] || 'info';
			},
		},
		{
			title: '流程状态',
			key: 'WorkflowStatus',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysPurchaseRequestBillView) => {
				const statusMap: Record<string, string> = {
					待提交: 'info',
					提交中: 'info',
					审核中: 'warning',
					已完成: 'success',
					已取消: 'danger',
				};
				return statusMap[row.WorkflowStatus || ''] || 'info';
			},
		},

		// 2️⃣ 核心业务信息
		{ title: '申请人', key: 'Applicant', type: 'text', isCheck: true },
		{ title: '申请日期', key: 'RequestDate', type: 'text', isCheck: true },
		{ title: '需求日期', key: 'NeedDate', type: 'text', isCheck: true },
		{ title: '总金额', key: 'Amount', type: 'text', isCheck: true },

		// 3️⃣ 采购分类信息
		{ title: '采购类型', key: 'PurchaseType', type: 'text', isCheck: true },
		{ title: '物料类型', key: 'MaterialType', type: 'text', isCheck: true },
		// { title: '采购方式', key: 'PurchaseMethod', type: 'text', isCheck: true },
		{ title: '紧急程度', key: 'UrgencyLevel', type: 'text', isCheck: true },
		{ title: '紧急采购原因', key: 'UrgencyReason', type: 'text', isCheck: true },

		// 4️⃣ 审批追踪信息
		{ title: '审批人', key: 'Approver', type: 'text', isCheck: true },
		{ title: '审批时间', key: 'ApprovalTime', type: 'text', isCheck: true },

		// 5️⃣ 组织归属信息
		{ title: '所属机构', key: 'OrgName', type: 'text', isCheck: true },
		{ title: '所属部门', key: 'GroupName', type: 'text', isCheck: true },

		// 6️⃣ 补充信息
		{ title: '附件', key: '', type: 'filePreview', isCheck: true, filePreviewCount: 1 },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysPurchaseRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysPurchaseRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysPurchaseRequestBillView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPurchaseRequestBillView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysPurchaseRequestBill/GetSysGroups', [], false).then((x) => (stateData.AllSysGroups = x)),
		other.getSelectList('/api/SysPurchaseRequestBill/GetSysOrgs', [], false).then((x) => (stateData.AllSysOrgs = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
